import java.io.*;
import java.util.Scanner;

public class FindFile {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要扫描的目录");
        File rootFile = new File(scanner.next());
        if(!rootFile.isDirectory()) {
            System.out.println("不是目录");
            return;
        }
        System.out.println("请输入要找的关键字");
        String word = scanner.next();
        scaDir(rootFile,word);
    }

    private static void scaDir(File rootFile, String word) {
        File[] files = rootFile.listFiles();
        if(files == null) {
            return;
        }
        for(File file : files) {
            System.out.println("搜索到当前路径 :" + file.getAbsolutePath());
            if(file.isFile()) {
                String content = readFile(file);
                if(content.equals(word)) {
                    System.out.println("找到包含关键词 :" + file.getAbsolutePath());
                }
            }else if(file.isDirectory()) {
                scaDir(file,word);
            }else {
                continue;
            }
        }
    }

    private static String readFile(File file) {
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(file)) {
            while(true) {
                int c = reader.read();
                if(c == -1) {
                    break;
                }
                stringBuilder.append((char)c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }
}
